import { getRequest } from "./api";

import { resetRouter } from "@/router";

export const initMenus = (router, store) => {
    if (store.state.routes.length > 0) {
        return
    }

    getRequest('system/cfg/menu').then(resp => {
        if (resp) {
            //格式化路由，将conponent由字符串转换成组件引入
            let fmtRoutes = formatRoutes(resp)
            //添加到路由
            //重置路由，该方法在router/index.js中定义
            resetRouter()

            //addRoutes方法即将被弃用,不建议使用
            fmtRoutes.forEach(route => {
                router.addRoute(route)
            })

            //保存路由到Vuex
            store.commit('initRoutes', fmtRoutes);

        }
    })

    function formatRoutes(routes) {
        let fmtRoutes = []
        routes.forEach(route => {
            let { path, name, component, iconCls, children } = route
            if (children && children instanceof Array) {
                children = formatRoutes(children)
            }
            let fmtRoute = {
                path,
                name,
                iconCls,
                children,
                component: () => {
                    if (component.startsWith('Home')) {
                        return import(`@/views/${component}.vue`)
                    } else if (component.startsWith('Emp')) {
                        return import(`@/views/emp/${component}.vue`)
                    } else if (component.startsWith('Per')) {
                        return import(`@/views/per/${component}.vue`)
                    } else if (component.startsWith('Sal')) {
                        return import(`@/views/sal/${component}.vue`)
                    } else if (component.startsWith('Sta')) {
                        return import(`@/views/sta/${component}.vue`)
                    } else if (component.startsWith('Sys')) {
                        return import(`@/views/sys/${component}.vue`)
                    }

                }
            }
            fmtRoutes.push(fmtRoute)
        });
        return fmtRoutes
    }
}